package com.foomia.truego.parsers.json;

import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.foomia.truego.types.Group;
import com.foomia.truego.types.TruegoType;


/**
 * Reference:
 * http://www.json.org/javadoc/org/json/JSONObject.html
 * http://www.json.org/javadoc/org/json/JSONArray.html
 * 
 * @author Mark Wyszomierski (markww@gmail.com)
 * @param <T>
 */

public class GroupParser extends AbstractParser<Group>{
	private Parser<? extends TruegoType> mSubParser;
	Group<TruegoType> group = new Group<TruegoType>();
    public GroupParser(Parser<? extends TruegoType> subParser) {
        mSubParser = subParser;
        group.setType("The distance in 500 meters");
    }
    
    /**
     * When we encounter a JSONObject in a GroupParser, we expect one attribute
     * named 'type', and then another JSONArray attribute.
     */
    public Group<TruegoType> parse(JSONObject json) throws JSONException {
    	
        //Group<LandtourType> group = new Group<LandtourType>();
        /*
        Iterator<String> it = (Iterator<String>)json.keys();
        while (it.hasNext()) {
            String key = it.next();
            if (key.equals("type")) {
                //group.setType(json.getString(key));
            } else {
                Object obj = json.get(key);
                if (obj instanceof JSONArray) {  
                    parse(group, (JSONArray)obj);
                } else {
                    throw new JSONException("Could not parse data.");
                }
            }
        }
        */
        TruegoType item = null;
        item = mSubParser.parse(json);
        group.add(item);
        return group;
    }
    
    /**
     * Here we are getting a straight JSONArray and do not expect the 'type' attribute.
     */
    @Override
    public Group parse(JSONArray array) {
  
        
        parse(group, array);
        return group;
    }
    
	private void parse(Group group, JSONArray array) {
		try {
			for (int i = 0, m = array.length(); i < m; i++) {
				Object element = array.get(i);
				TruegoType item = null;
				if (element instanceof JSONArray) {
					item = mSubParser.parse((JSONArray) element);
				} else {
					item = mSubParser.parse((JSONObject) element);
				}
				group.add(item);
				/*
				if (i + 1 == m) {
					group.add(item);
				}
				*/
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
